Skip to content

Instantiating objects#11

Open
Butcher3Years wants to merge 12 commits intomainfrom
Instantiating--objects
Open

Instantiating objects#11
Butcher3Years wants to merge 12 commits intomainfrom
Instantiating--objects

Conversation

@Butcher3Years
Copy link
Copy Markdown
Owner

Stack vs Heap in C++: Where Your Objects Live

In C++, when you create an object (class/struct instance), memory comes from one of two main places: the stack or the heap.
This choice affects speed, safety, lifetime, and size limits.

Quick Comparison Table

Feature Stack Allocation Heap Allocation
How to create Entity e("Cherno");
or int x = 42;
Entity* ptr = new Entity("Cherno");
Memory location Stack (fast, near CPU cache) Heap (dynamic pool, farther away)
Lifetime Until scope ends (function return, block end) Until you delete it (or smart pointer cleans)
Allocation speed Very fast (just move stack pointer) Slower (search for free block + overhead)
Deallocation Automatic (when scope ends) Manual (delete ptr;) — easy to forget!
Size limit Small (usually 1–8 MB total) Large (limited by system RAM)
Common issues Stack overflow (too deep recursion/big locals) Memory leaks, dangling pointers, fragmentation
Best for Local vars, temp objects, small/fixed data Dynamic size, long-lived, shared, big objects

Stack Allocation (Automatic / Local)

  • Super fast & safe — compiler handles everything.
  • Objects live only in current scope (function/block).
  • No new/delete needed → no leaks!
void func() {
    Entity local("Stack Entity");   // ← stack-allocated
    // local dies automatically when func() ends
}

Entity* createEntity() {
    Entity* dynamic = new Entity("Heap Entity");   // ← heap-allocated
    return dynamic;   // safe to return pointer
}

// Later...
Entity* e = createEntity();
delete e;   // MUST delete or → memory leak!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant